﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Logging;
using MayfairFramework.Transaction.NHibernate;
using NHibernate;
using NHibernate.Cfg;
using System.Reflection;

namespace MayfairFramework.Common.Service.NHibernate
{
    public class NHibernateBasicService : BasicService
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pk"></param>
        /// <returns></returns>
        public override T FindByPK<T>(object pk)
        {
            ISession session = NHibernateUtils.GetSession();
            T ret = session.Load<T>(pk);
            session.Close();
            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objects"></param>
        public override void Insert<T>(params T[] objects)
        {
                using (ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory())
                {
                    using (ISession session = sessionFactory.OpenSession())
                    {
                        using (ITransaction transaction = session.BeginTransaction())
                        {
                            try
                            {
                                foreach (T o in objects)
                                {
                                    session.Save(o);
                                }
                                transaction.Commit();
                            }
                            catch (Exception ex)
                            {
                                log.Warn(ex.Message, ex);
                                if (sessionFactory != null && session != null)
                                {
                                    if (transaction.IsActive == true)
                                    {
                                        transaction.Rollback();
                                    }
                                }
                                throw ex;
                            }
                        }
                    }
                }
            }

        public override void Update<T>(params T[] objects)
        {
            throw new NotImplementedException();
        }

        public override void Delete<T>(params T[] objects)
        {
            throw new NotImplementedException();
        }
    }
}